<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>后台管理系统 - 数码商城</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        }

        body {
            background-color: #f4f4f4;
            display: flex;
            min-height: 100vh;
        }

        /* Sidebar */
        .sidebar {
            width: 250px;
            background: #2c3e50;
            height: 100vh;
            position: fixed;
            color: white;
            padding: 20px 0;
            overflow-y: auto;
        }

        .logo {
            text-align: center;
            padding: 20px;
            border-bottom: 1px solid #34495e;
            margin-bottom: 20px;
        }

        .logo h2 {
            font-size: 1.5rem;
            font-weight: 600;
        }

        .menu-item {
            padding: 15px 25px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 10px;
            transition: background 0.3s;
            border-left: 3px solid transparent;
        }

        .menu-item:hover,
        .menu-item.active {
            background: #34495e;
            border-left-color: #3498db;
        }

        .menu-item i {
            width: 20px;
            font-size: 1.1rem;
        }

        /* Main Content */
        .main-content {
            margin-left: 250px;
            padding: 20px;
            width: calc(100% - 250px);
            min-height: 100vh;
        }

        .header {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
        }

        .search-bar {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

        .search-bar input {
            padding: 8px 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
            width: 300px;
            font-size: 14px;
        }

        .search-bar button {
            padding: 8px 20px;
            background: #3498db;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background 0.2s;
        }

        .search-bar button:hover {
            background: #2980b9;
        }

        /* Content Sections */
        .content-section {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
            display: none;
        }

        .content-section.active {
            display: block;
        }

        .section-title {
            font-size: 1.5rem;
            font-weight: 600;
            margin-bottom: 20px;
            color: #2c3e50;
        }

        /* Tables */
        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .data-table th,
        .data-table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }

        .data-table th {
            background: #f8f9fa;
            font-weight: 600;
            color: #2c3e50;
            font-size: 14px;
        }

        .data-table tr:hover {
            background: #f8f9fa;
        }

        .action-btn {
            padding: 6px 12px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 5px;
            font-size: 12px;
            transition: all 0.2s;
        }

        .edit-btn {
            background: #3498db;
            color: white;
        }

        .edit-btn:hover {
            background: #2980b9;
        }

        .delete-btn {
            background: #e74c3c;
            color: white;
        }

        .delete-btn:hover {
            background: #c0392b;
        }

        .view-btn {
            background: #27ae60;
            color: white;
        }

        .view-btn:hover {
            background: #229954;
        }

        /* Buttons */
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.2s;
            text-decoration: none;
            display: inline-block;
        }

        .btn-primary {
            background: #3498db;
            color: white;
        }

        .btn-primary:hover {
            background: #2980b9;
            transform: translateY(-1px);
        }

        .btn-success {
            background: #27ae60;
            color: white;
        }

        .btn-success:hover {
            background: #229954;
            transform: translateY(-1px);
        }

        .btn-danger {
            background: #e74c3c;
            color: white;
        }

        .btn-danger:hover {
            background: #c0392b;
            transform: translateY(-1px);
        }

        /* Forms */
        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #2c3e50;
            font-weight: 500;
            font-size: 14px;
        }

        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
            transition: border-color 0.2s, box-shadow 0.2s;
        }

        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #3498db;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
        }

        .form-group textarea {
            height: 100px;
            resize: vertical;
        }

        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
        }

        /* Modal */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            overflow-y: auto;
            padding: 20px;
        }

        .modal-content {
            background: white;
            width: 100%;
            max-width: 600px;
            margin: 50px auto;
            padding: 30px;
            border-radius: 12px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            position: relative;
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }

        .modal-header h3 {
            font-size: 1.5rem;
            font-weight: 600;
            color: #2c3e50;
        }

        .close-modal {
            cursor: pointer;
            font-size: 24px;
            color: #666;
            background: none;
            border: none;
            padding: 5px;
            border-radius: 4px;
            transition: background 0.2s;
        }

        .close-modal:hover {
            background: #f8f9fa;
            color: #333;
        }

        .modal-footer {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 25px;
            padding-top: 20px;
            border-top: 1px solid #eee;
        }

        /* Status badges */
        .status-badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
        }

        .status-active {
            background: #d4edda;
            color: #155724;
        }

        .status-inactive {
            background: #f8d7da;
            color: #721c24;
        }

        .status-pending {
            background: #fff3cd;
            color: #856404;
        }

        /* Responsive */
        @media (max-width: 768px) {
            .sidebar {
                width: 200px;
            }

            .main-content {
                margin-left: 200px;
                width: calc(100% - 200px);
                padding: 15px;
            }

            .header {
                flex-direction: column;
                align-items: stretch;
            }

            .search-bar {
                flex-direction: column;
            }

            .search-bar input {
                width: 100%;
            }

            .form-row {
                grid-template-columns: 1fr;
            }

            .modal-content {
                margin: 20px auto;
                padding: 20px;
            }
        }

        @media (max-width: 480px) {
            .sidebar {
                width: 100%;
                height: auto;
                position: relative;
            }

            .main-content {
                margin-left: 0;
                width: 100%;
            }

            .data-table {
                font-size: 12px;
            }

            .data-table th,
            .data-table td {
                padding: 8px;
            }
        }

        /* Loading states */
        .loading {
            opacity: 0.6;
            pointer-events: none;
        }

        .spinner {
            display: inline-block;
            width: 16px;
            height: 16px;
            border: 2px solid #ffffff;
            border-radius: 50%;
            border-top-color: transparent;
            animation: spin 1s ease-in-out infinite;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }

        /* Empty state */
        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: #666;
        }

        .empty-state i {
            font-size: 3rem;
            color: #ddd;
            margin-bottom: 15px;
        }

        .status-badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            color: white;
        }

        .status-pending {
            background-color: #f39c12;
            /* a nice orange */
        }

        .status-shipped {
            background-color: #27ae60;
            /* a nice green */
        }

        .ship-btn {
            background: #3498db;
            color: white;
        }

        .ship-btn:hover {
            background: #2980b9;
        }
    </style>
</head>

<body>
    <!-- Sidebar -->
    <div class="sidebar">
        <div class="logo">
            <h2>后台管理系统</h2>
        </div>
        <div class="menu-item active" data-section="products">
            <i>📦</i>
            <span>商品管理</span>
        </div>
        <div class="menu-item" data-section="categories">
            <i>🏷️</i>
            <span>分类管理</span>
        </div>
        <div class="menu-item" data-section="orders">
            <i>🛒</i>
            <span>订单管理</span>
        </div>
        <div class="menu-item" data-section="users">
            <i>👥</i>
            <span>用户管理</span>
        </div>
    </div>

    <!-- Main Content -->
    <div class="main-content">
        <!-- Products Section -->
        <div class="content-section active" id="products">
            <div class="header">
                <h2 class="section-title">商品管理</h2>
                <div class="search-bar">
                    <input type="text" id="productSearch" placeholder="搜索商品名称..."
                        onkeypress="handleSearchKeyPress(event)">
                    <button onclick="searchProducts()">搜索</button>
                    <button class="btn btn-primary" onclick="showAddProductModal()">添加商品</button>
                </div>
            </div>

            <div class="table-container">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>图片</th>
                            <th>商品名称</th>
                            <th>价格</th>
                            <th>库存</th>
                            <th>分类</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="productsTableBody">
                        <tr>
                            <td colspan="8" class="empty-state">
                                <div>📦</div>
                                <p>暂无商品数据</p>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Orders Section -->
        <div class="content-section" id="orders">
            <div class="header">
                <h2 class="section-title">订单管理</h2>
                <div class="search-bar">
                    <input type="text" id="orderSearchInput" placeholder="输入用户名搜索订单">
                    <button onclick="searchOrders()">搜索</button>
                </div>
            </div>

            <div class="table-container" id="orders-table-container">
                <!-- Orders table will be dynamically injected here -->
                <div class="empty-state">
                    <div>🛒</div>
                    <p>暂无订单数据</p>
                </div>
            </div>
        </div>

        <!-- Categories Section -->
        <div class="content-section" id="categories">
            <div class="header">
                <h2 class="section-title">分类管理</h2>
                <button class="btn btn-primary" onclick="showAddCategoryModal()">添加分类</button>
            </div>

            <div class="table-container">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>分类名称</th>
                            <th>描述</th>
                            <th>商品数量</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="categoriesTableBody">
                        <tr>
                            <td colspan="5" class="empty-state">
                                <div>🏷️</div>
                                <p>暂无分类数据</p>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Users Section -->
        <div class="content-section" id="users">
            <div class="header">
                <h2 class="section-title">用户管理</h2>
                <div class="search-bar">
                    <input type="text" id="userSearch" placeholder="搜索用户名...">
                    <button onclick="searchUsers()">搜索</button>
                </div>
            </div>

            <div class="table-container">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>用户名</th>
                            <th>邮箱</th>
                            <th>电话</th>
                            <th>角色</th>
                            <th>注册时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="usersTableBody">
                        <tr>
                            <td colspan="7" class="empty-state">
                                <div>👥</div>
                                <p>暂无用户数据</p>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Add Product Modal -->
    <div class="modal" id="addProductModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>添加商品</h3>
                <button class="close-modal" onclick="closeModal('addProductModal')">&times;</button>
            </div>
            <form id="addProductForm">
                <div class="form-row">
                    <div class="form-group">
                        <label>商品名称 *</label>
                        <input type="text" name="name" required>
                    </div>
                    <div class="form-group">
                        <label>价格 *</label>
                        <input type="number" name="price" step="0.01" min="0" required>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>库存 *</label>
                        <input type="number" name="stock" min="0" required>
                    </div>
                    <div class="form-group">
                        <label>分类 *</label>
                        <select name="categoryId" required>
                            <option value="">请选择分类</option>
                            <option value="1">智能手机</option>
                            <option value="2">笔记本电脑</option>
                            <option value="3">音频设备</option>
                            <option value="4">平板电脑</option>
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <label>商品图片</label>
                    <input type="file" name="image" accept="image/*">
                    <input type="hidden" name="imageUrl" id="imageUrlInput">
                </div>
                <div class="form-group">
                    <label>商品描述</label>
                    <textarea name="description" placeholder="请输入商品详细描述..."></textarea>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn" onclick="closeModal('addProductModal')">取消</button>
                    <button type="submit" class="btn btn-primary">保存商品</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Add Category Modal -->
    <div class="modal" id="addCategoryModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>添加分类</h3>
                <button class="close-modal" onclick="closeModal('addCategoryModal')">&times;</button>
            </div>
            <form id="addCategoryForm">
                <div class="form-group">
                    <label>分类名称 *</label>
                    <input type="text" name="name" required placeholder="请输入分类名称">
                </div>
                <div class="form-group">
                    <label>分类描述</label>
                    <textarea name="description" placeholder="请输入分类描述..."></textarea>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn" onclick="closeModal('addCategoryModal')">取消</button>
                    <button type="submit" class="btn btn-primary">保存分类</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Edit Product Modal -->
    <div class="modal" id="editProductModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>编辑商品</h3>
                <button class="close-modal" onclick="closeModal('editProductModal')">&times;</button>
            </div>
            <form id="editProductForm">
                <input type="hidden" name="id">
                <div class="form-row">
                    <div class="form-group">
                        <label>商品名称 *</label>
                        <input type="text" name="name" required>
                    </div>
                    <div class="form-group">
                        <label>价格 *</label>
                        <input type="number" name="price" step="0.01" min="0" required>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>库存 *</label>
                        <input type="number" name="stock" min="0" required>
                    </div>
                    <div class="form-group">
                        <label>分类 *</label>
                        <select name="categoryId" required>
                            <option value="">请选择分类</option>
                            <option value="1">智能手机</option>
                            <option value="2">笔记本电脑</option>
                            <option value="3">音频设备</option>
                            <option value="4">平板电脑</option>
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <label>商品图片</label>
                    <input type="file" name="image" accept="image/*">
                    <input type="hidden" name="imageUrl">
                </div>
                <div class="form-group">
                    <label>商品描述</label>
                    <textarea name="description"></textarea>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn" onclick="closeModal('editProductModal')">取消</button>
                    <button type="submit" class="btn btn-primary">更新商品</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        // 分类数据缓存
        let allCategories = [];

        // 动态加载所有分类
        async function fetchAllCategories() {
            try {
                const resp = await fetch('/categories');
                allCategories = await resp.json();
                renderCategorySelects();
                renderCategoryTable();
            } catch (e) {
                console.error('加载分类失败', e);
            }
        }

        // 渲染商品添加/编辑下拉框
        function renderCategorySelects() {
            const selects = document.querySelectorAll('select[name="categoryId"]');
            selects.forEach(select => {
                const val = select.value;
                select.innerHTML = '<option value="">请选择分类</option>' +
                    allCategories.map(cat => `<option value="${cat.id}">${cat.name}</option>`).join('');
                if (val) select.value = val;
            });
        }

        // 分类管理表格渲染
        function renderCategoryTable() {
            const tbody = document.getElementById('categoriesTableBody');
            if (!tbody) return;
            if (allCategories.length === 0) {
                tbody.innerHTML = `<tr><td colspan="5" class="empty-state"><div>🏷️</div><p>暂无分类数据</p></td></tr>`;
                return;
            }
            tbody.innerHTML = allCategories.map(cat => `
                <tr>
                    <td>${cat.id}</td>
                    <td>${cat.name}</td>
                    <td>${cat.description || '-'}</td>
                    <td>${cat.productCount || 0}</td>
                    <td>
                        <button class="action-btn edit-btn" onclick="showEditCategoryModal(${cat.id})">编辑</button>
                        <button class="action-btn delete-btn" onclick="deleteCategory(${cat.id})">删除</button>
                    </td>
                </tr>
            `).join('');
        }

        // 编辑分类弹窗
        function showEditCategoryModal(id) {
            const cat = allCategories.find(c => c.id === id);
            if (!cat) return;
            const name = prompt('请输入新分类名称', cat.name);
            if (name === null) return;
            const description = prompt('请输入新分类描述', cat.description || '');
            if (description === null) return;
            updateCategory(id, name, description);
        }

        // 更新分类（PUT）
        async function updateCategory(id, name, description) {
            try {
                const resp = await fetch('/categories', {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ id, name, description })
                });
                if (resp.ok) {
                    alert('分类更新成功！');
                    fetchAllCategories();
                } else {
                    alert('更新失败');
                }
            } catch (e) {
                alert('网络错误');
            }
        }

        // 删除分类（DELETE，参数名为categoryId）
        async function deleteCategory(id) {
            if (!confirm('确定要删除这个分类吗？')) return;
            try {
                const resp = await fetch(`/categories?categoryId=${id}`, { method: 'DELETE' });
                if (resp.ok) {
                    const result = await resp.text();
                    if (result === '删除成功') {
                        alert('删除成功');
                        fetchAllCategories();
                    } else {
                        alert(result);
                    }
                } else {
                    alert('删除失败');
                }
            } catch (e) {
                alert('网络错误');
            }
        }

        // 新增分类（POST，不带id）
        async function handleAddCategory(e) {
            e.preventDefault();
            const formData = new FormData(e.target);
            try {
                const response = await fetch('/categories', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        name: formData.get('name'),
                        description: formData.get('description')
                    })
                });
                if (response.ok) {
                    alert('分类添加成功！');
                    closeModal('addCategoryModal');
                    fetchAllCategories();
                } else {
                    alert('添加失败，请重试');
                }
            } catch (error) {
                console.error('Error adding category:', error);
                alert('网络错误，请重试');
            }
        }

        // 修改商品表单数据
        async function loadProductData(productId) {
            try {
                const response = await fetch(`/getById?id=${productId}`);
                const product = await response.json();
                if (product) {
                    const form = document.getElementById('editProductForm');
                    form.querySelector('input[name="id"]').value = product.id;
                    form.querySelector('input[name="name"]').value = product.name;
                    form.querySelector('input[name="price"]').value = product.price;
                    form.querySelector('input[name="stock"]').value = product.stock;
                    await fetchAllCategories(); // 确保分类下拉是最新的
                    form.querySelector('select[name="categoryId"]').value = product.categoryId;
                    form.querySelector('textarea[name="description"]').value = product.description || '';
                    const imageUrlInput = form.querySelector('input[name="imageUrl"]');
                    if (imageUrlInput) imageUrlInput.value = product.imageUrl || '';
                }
            } catch (e) { alert('加载商品失败'); }
        }

        // 商品添加弹窗时刷新分类下拉
        function showAddProductModal() {
            fetchAllCategories();
            document.getElementById('addProductModal').style.display = 'block';
            document.body.style.overflow = 'hidden';
        }

        // 页面初始化
        document.addEventListener('DOMContentLoaded', async function () {
            await fetchAllCategories(); // 先加载分类
            loadProducts();            // 再加载商品
        });

        // 修改tab切换时的加载顺序
        async function loadSectionData(section) {
            switch (section) {
                case 'products':
                    await fetchAllCategories();
                    loadProducts();
                    break;
                case 'orders':
                    loadOrders();
                    break;
                case 'categories':
                    fetchAllCategories();
                    break;
                case 'users':
                    loadUsers();
                    break;
            }
        }

        // 菜单切换
        document.querySelectorAll('.menu-item').forEach(item => {
            item.addEventListener('click', function () {
                // 更新菜单激活状态
                document.querySelectorAll('.menu-item').forEach(i => i.classList.remove('active'));
                this.classList.add('active');
                // 更新内容区域显示
                const sectionId = this.dataset.section;
                document.querySelectorAll('.content-section').forEach(section => {
                    section.classList.remove('active');
                });
                document.getElementById(sectionId).classList.add('active');

                // 加载对应数据
                loadSectionData(sectionId);
            });
        });

        // 表单提交处理
        document.getElementById('addCategoryForm').addEventListener('submit', handleAddCategory);
        document.getElementById('editProductForm').addEventListener('submit', handleEditProduct);

        // 初始化加载数据
        loadSectionData('products');

        function showAddCategoryModal() {
            document.getElementById('addCategoryModal').style.display = 'block';
            document.body.style.overflow = 'hidden';
        }

        // 显示修改商品表单
        function showEditProductModal(productId) {
            // 根据ID获取商品数据并填充到表单
            loadProductData(productId);
            document.getElementById('editProductModal').style.display = 'block';
            document.body.style.overflow = 'hidden';
        }

        // 显示当前图片预览
        function showCurrentImagePreview(imageUrl) {
            const imageInput = document.querySelector('#editProductModal input[name="image"]');
            const existingPreview = imageInput.parentNode.querySelector('.current-image-preview');
            if (existingPreview) {
                existingPreview.remove();
            }

            const preview = document.createElement('div');
            preview.className = 'current-image-preview';
            preview.style.cssText = `
                margin-top: 10px;
                text-align: center;
            `;

            const img = document.createElement('img');
            img.src = imageUrl;
            img.style.cssText = `
                max-width: 150px;
                max-height: 150px;
                border-radius: 4px;
                border: 1px solid #ddd;
            `;
            img.onerror = function () {
                this.style.display = 'none';
                preview.innerHTML = '<p style="color: #999; font-size: 12px;">当前图片加载失败</p>';
            };

            preview.appendChild(img);
            imageInput.parentNode.appendChild(preview);
        }

        //关闭模态框（Modal）并清理相关数据。
        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
            document.body.style.overflow = 'auto';
            // 清空表单
            document.querySelector(`#${modalId} form`).reset();

            // 清理图片预览
            const modal = document.getElementById(modalId);
            const imagePreviews = modal.querySelectorAll('.image-preview, .current-image-preview');
            imagePreviews.forEach(preview => preview.remove());

            // 清空隐藏的imageUrl字段
            const imageUrlInputs = modal.querySelectorAll('input[name="imageUrl"]');
            imageUrlInputs.forEach(input => input.value = '');
        }

        // 点击模态框外部关闭
        window.addEventListener('click', function (event) {
            if (event.target.classList.contains('modal')) {
                event.target.style.display = 'none';
                document.body.style.overflow = 'auto';
            }
        });

        // 商品数据加载函数
        async function loadProducts() {
            try {
                const response = await fetch('/pageProduct?pageNum=1&pageSize=100');
                const data = await response.json();

                const tbody = document.getElementById('productsTableBody');
                if (data.list && data.list.length > 0) {
                    tbody.innerHTML = data.list.map(product => `
                    <tr>
                        <td>${product.id}</td>
                        <td>
                            <img src="${product.imageUrl || '/static/images/default-product.jpg'}" 
                                 alt="Product Image" 
                                 style="width: 60px; height: 60px; object-fit: cover; border-radius: 4px;"
                                 onerror="this.src=''">
                        </td>
                        <td>${product.name}</td>
                        <td>¥${product.price}</td>
                        <td>${product.stock}</td>
                        <td>${getCategoryName(product.categoryId)}</td>
                        <td><span class="status-badge status-active">上架中</span></td>
                        <td>
                            <button class="action-btn view-btn" onclick="viewProduct(${product.id})">查看</button>
                            <button class="action-btn edit-btn" onclick="showEditProductModal(${product.id})">编辑</button>
                            <button class="action-btn delete-btn" onclick="deleteProduct(${product.id})">删除</button>
                        </td>
                    </tr>
                `).join('');
                } else {
                    tbody.innerHTML = `
                    <tr>
                        <td colspan="8" class="empty-state">
                            <div>📦</div>
                            <p>暂无商品数据</p>
                        </td>
                    </tr>
                `;
                }
            } catch (error) {
                console.error('Error loading products:', error);
            }
        }

        // 加载订单数据
        async function loadOrders() {
            const container = document.getElementById('orders-table-container');
            container.innerHTML = `<div class="empty-state"><div class="spinner"></div><p>正在加载订单...</p></div>`; // Show loading state
            try {
                const response = await fetch('/admin/orders');
                if (!response.ok) {
                    throw new Error(`服务器响应错误: ${response.status}`);
                }
                const ordersData = await response.json();
                renderOrdersTable(ordersData);
            } catch (error) {
                console.error('Error loading orders:', error);
                container.innerHTML = `<div class="empty-state" style="color: #e74c3c;"><div>❌</div><p>加载订单失败，请检查网络或联系管理员。</p></div>`;
            }
        }

        // 加载用户数据
        async function loadUsers() {
            try {
                const response = await fetch('/userList');
                const users = await response.json();
                const tbody = document.getElementById('usersTableBody');
                if (users && users.length > 0) {
                    tbody.innerHTML = users.map(user => `
                        <tr>
                            <td>${user.id}</td>
                            <td>${user.username}</td>
                            <td>${user.email || ''}</td>
                            <td>${user.phone || ''}</td>
                            <td><span class="status-badge ${user.role === 1 ? 'status-active' : 'status-inactive'}">${user.role === 1 ? '管理员' : '普通用户'}</span></td>
                            <td>${user.createdAt ? (user.createdAt.substring ? user.createdAt.substring(0, 10) : user.createdAt) : ''}</td>
                            <td>
                                <button class="action-btn edit-btn" onclick="editUser(${user.id})">编辑</button>
                                <button class="action-btn delete-btn" onclick="deleteUser(${user.id})">删除</button>
                            </td>
                        </tr>
                    `).join('');
                } else {
                    tbody.innerHTML = `
                        <tr>
                            <td colspan="7" class="empty-state">
                                <div>👥</div>
                                <p>暂无用户数据</p>
                            </td>
                        </tr>
                    `;
                }
            } catch (error) {
                console.error('加载用户失败:', error);
                const tbody = document.getElementById('usersTableBody');
                tbody.innerHTML = `
                    <tr>
                        <td colspan="7" class="empty-state">
                            <div>❌</div>
                            <p>加载用户失败</p>
                        </td>
                    </tr>
                `;
            }
        }

        // 表单处理函数
        async function handleEditProduct(e) {
            e.preventDefault();

            const form = e.target;
            const product = {
                id: parseInt(form.querySelector('input[name="id"]').value),
                name: form.querySelector('input[name="name"]').value,
                price: parseFloat(form.querySelector('input[name="price"]').value),
                stock: parseInt(form.querySelector('input[name="stock"]').value),
                categoryId: parseInt(form.querySelector('select[name="categoryId"]').value),
                description: form.querySelector('textarea[name="description"]').value,
                imageUrl: form.querySelector('input[name="imageUrl"]') ? form.querySelector('input[name="imageUrl"]').value : ''
            };

            try {
                const response = await fetch('/update', {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(product)
                });

                const data = await response.json();
                if (data.success) {
                    alert('商品更新成功！');
                    closeModal('editProductModal');
                    loadProducts(); // 刷新商品列表
                } else {
                    alert('更新失败：' + data.message);
                }
            } catch (error) {
                console.error('更新商品失败:', error);
                alert('更新失败，请重试');
            }
        }

        // 回车键搜索
        function handleSearchKeyPress(event) {
            if (event.key === 'Enter') {
                searchProducts();
            }
        }

        // 搜索商品函数
        async function searchProducts() {
            const searchTerm = document.getElementById('productSearch').value.trim();
            if (!searchTerm) {
                // 如果搜索词为空，加载所有商品
                loadProducts();
                return;
            }

            try {
                const response = await fetch(`/getByName?name=${encodeURIComponent(searchTerm)}`);
                const products = await response.json();

                const tbody = document.getElementById('productsTableBody');
                if (products && products.length > 0) {
                    tbody.innerHTML = products.map(product => `
                    <tr>
                        <td>${product.id}</td>
                        <td>
                            <img src="${product.imageUrl || '/static/images/default-product.jpg'}" 
                                 alt="Product Image" 
                                 style="width: 60px; height: 60px; object-fit: cover; border-radius: 4px;"
                                 onerror="this.src=''">
                        </td>
                        <td>${product.name}</td>
                        <td>¥${product.price}</td>
                        <td>${product.stock}</td>
                        <td>${getCategoryName(product.categoryId)}</td>
                        <td><span class="status-badge status-active">上架中</span></td>
                        <td>
                            <button class="action-btn view-btn" onclick="viewProduct(${product.id})">查看</button>
                            <button class="action-btn edit-btn" onclick="showEditProductModal(${product.id})">编辑</button>
                            <button class="action-btn delete-btn" onclick="deleteProduct(${product.id})">删除</button>
                        </td>
                    </tr>
                `).join('');
                } else {
                    tbody.innerHTML = `
                    <tr>
                        <td colspan="8" class="empty-state">
                            <div>🔍</div>
                            <p>未找到匹配的商品</p>
                        </td>
                    </tr>
                `;
                }
            } catch (error) {
                console.error('搜索商品失败:', error);
                alert('搜索失败，请重试');
            }
        }

        //搜索订单
        function searchOrders() {
            const username = document.getElementById('orderSearchInput').value.trim();
            if (username) {
                searchOrdersByUsername(username);
            } else {
                // 如果搜索框为空，加载所有订单
                loadOrders();
            }
        }

        async function searchOrdersByUsername(username) {
            const response = await fetch(`/admin/userOrder?username=${encodeURIComponent(username)}`);
            const orders = await response.json();
            // 渲染订单列表
            renderOrdersTable(orders);
        }

        //搜索用户
        function searchUsers() {
            const searchTerm = document.getElementById('userSearch').value.trim();
            if (!searchTerm) {
                loadUsers();
                return;
            }
            fetch(`/userListByUsername?username=${encodeURIComponent(searchTerm)}`)
                .then(resp => resp.json())
                .then(users => {
                    const tbody = document.getElementById('usersTableBody');
                    if (users && users.length > 0) {
                        tbody.innerHTML = users.map(user => `
                            <tr>
                                <td>${user.id}</td>
                                <td>${user.username}</td>
                                <td>${user.email || ''}</td>
                                <td>${user.phone || ''}</td>
                                <td><span class="status-badge ${user.role === 1 ? 'status-active' : 'status-inactive'}">${user.role === 1 ? '管理员' : '普通用户'}</span></td>
                                <td>${user.createdAt ? (user.createdAt.substring ? user.createdAt.substring(0, 10) : user.createdAt) : ''}</td>
                                <td>
                                    <button class="action-btn edit-btn" onclick="editUser(${user.id})">编辑</button>
                                    <button class="action-btn delete-btn" onclick="deleteUser(${user.id})">删除</button>
                                </td>
                            </tr>
                        `).join('');
                    } else {
                        tbody.innerHTML = `
                            <tr>
                                <td colspan="7" class="empty-state">
                                    <div>👥</div>
                                    <p>未找到匹配的用户</p>
                                </td>
                            </tr>
                        `;
                    }
                })
                .catch(error => {
                    console.error('搜索用户失败:', error);
                    const tbody = document.getElementById('usersTableBody');
                    tbody.innerHTML = `
                        <tr>
                            <td colspan="7" class="empty-state">
                                <div>❌</div>
                                <p>搜索用户失败</p>
                            </td>
                        </tr>
                    `;
                });
        }

        // 辅助函数
        function getCategoryName(categoryId) {
            const category = allCategories.find(cat => cat.id == categoryId);
            return category ? category.name : '未知分类';
        }

        // 操作函数
        async function viewProduct(id) {
            try {
                const response = await fetch(`/getById?id=${id}`);
                const product = await response.json();

                if (product) {
                    // 显示商品详情弹窗
                    showProductDetailModal(product);
                } else {
                    alert('商品不存在！');
                }
            } catch (error) {
                console.error('获取商品详情失败:', error);
                alert('获取商品详情失败，请重试');
            }
        }

        // 显示商品详情弹窗
        function showProductDetailModal(product) {
            // 创建详情弹窗
            const modal = document.createElement('div');
            modal.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.5);
                z-index: 1000;
                display: flex;
                justify-content: center;
                align-items: center;
            `;

            modal.innerHTML = `
                <div style="
                    background: white;
                    padding: 30px;
                    border-radius: 12px;
                    max-width: 700px;
                    width: 90%;
                    max-height: 80vh;
                    overflow-y: auto;
                    position: relative;
                ">
                    <button onclick="this.closest('.product-detail-modal').remove()" style="
                        position: absolute;
                        top: 15px;
                        right: 20px;
                        background: none;
                        border: none;
                        font-size: 24px;
                        cursor: pointer;
                        color: #666;
                    ">&times;</button>
                    
                    <h2 style="margin: 0 0 20px 0; color: #333; text-align: center;">商品详情</h2>
                    
                    <div style="display: flex; gap: 30px; margin-bottom: 25px;">
                        <img src="${product.imageUrl || '/static/images/default-product.jpg'}" 
                             alt="${product.name}" 
                             style="width: 250px; height: 250px; object-fit: cover; border-radius: 8px; border: 1px solid #ddd;"
                             onerror="this.src=''">
                        <div style="flex: 1;">
                            <table style="width: 100%; border-collapse: collapse;">
                                <tr>
                                    <td style="padding: 8px 0; font-weight: bold; color: #333; width: 100px;">商品ID:</td>
                                    <td style="padding: 8px 0; color: #666;">${product.id}</td>
                                </tr>
                                <tr>
                                    <td style="padding: 8px 0; font-weight: bold; color: #333;">商品名称:</td>
                                    <td style="padding: 8px 0; color: #666;">${product.name}</td>
                                </tr>
                                <tr>
                                    <td style="padding: 8px 0; font-weight: bold; color: #333;">价格:</td>
                                    <td style="padding: 8px 0; color: #e74c3c; font-size: 18px; font-weight: bold;">¥${product.price.toFixed(2)}</td>
                                </tr>
                                <tr>
                                    <td style="padding: 8px 0; font-weight: bold; color: #333;">库存:</td>
                                    <td style="padding: 8px 0; color: #666;">${product.stock}</td>
                                </tr>
                                <tr>
                                    <td style="padding: 8px 0; font-weight: bold; color: #333;">分类:</td>
                                    <td style="padding: 8px 0; color: #666;">${getCategoryName(product.categoryId)}</td>
                                </tr>
                                <tr>
                                    <td style="padding: 8px 0; font-weight: bold; color: #333;">创建时间:</td>
                                    <td style="padding: 8px 0; color: #666;">${product.createdAt ? new Date(product.createdAt).toLocaleString() : '未知'}</td>
                                </tr>
                            </table>
                        </div>
                    </div>
                    
                    ${product.description ? `
                    <div style="border-top: 1px solid #eee; padding-top: 20px;">
                        <h3 style="margin: 0 0 15px 0; color: #333;">商品描述</h3>
                        <p style="color: #666; line-height: 1.6; margin: 0; background: #f8f9fa; padding: 15px; border-radius: 6px;">${product.description}</p>
                    </div>
                    ` : ''}
                    
                    <div style="margin-top: 25px; text-align: center;">
                        <button onclick="showEditProductModal(${product.id}); this.closest('.product-detail-modal').remove();" 
                                style="
                                    background: #3498db;
                                    color: white;
                                    border: none;
                                    padding: 10px 20px;
                                    border-radius: 6px;
                                    cursor: pointer;
                                    font-size: 14px;
                                    margin-right: 10px;
                                ">
                            编辑商品
                        </button>
                        <button onclick="this.closest('.product-detail-modal').remove()" 
                                style="
                                    background: #95a5a6;
                                    color: white;
                                    border: none;
                                    padding: 10px 20px;
                                    border-radius: 6px;
                                    cursor: pointer;
                                    font-size: 14px;
                                ">
                            关闭
                        </button>
                    </div>
                </div>
            `;

            modal.className = 'product-detail-modal';
            document.body.appendChild(modal);

            // 点击背景关闭弹窗
            modal.addEventListener('click', function (e) {
                if (e.target === modal) {
                    modal.remove();
                }
            });
        }

        //删除商品
        async function deleteProduct(id) {
            if (confirm('确定要删除这个商品吗？此操作不可恢复！')) {
                try {
                    const response = await fetch(`/delete?id=${id}`, {
                        method: 'DELETE'
                    });

                    if (response.ok) {
                        const result = await response.text();
                        if (result === '删除成功') {
                            alert('商品删除成功！');
                            loadProducts(); // 刷新商品列表
                        } else {
                            alert('删除失败：' + result);
                        }
                    } else {
                        alert('删除失败，请重试');
                    }
                } catch (error) {
                    console.error('删除商品失败:', error);
                    alert('删除失败，请重试');
                }
            }
        }

        function editUser(id) {
            // 1. 获取当前用户数据
            fetch('/userList')
                .then(resp => resp.json())
                .then(users => {
                    const user = users.find(u => u.id === id);
                    if (!user) {
                        alert('用户不存在');
                        return;
                    }
                    // 2. 弹窗表单
                    showEditUserModal(user);
                });
        }

        function showEditUserModal(user) {
            // 创建弹窗
            const modal = document.createElement('div');
            modal.style.cssText = `
                position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; background: rgba(0,0,0,0.4); z-index: 2000; display: flex; align-items: center; justify-content: center;`;
            modal.innerHTML = `
                <div style="background: #fff; padding: 30px 40px; border-radius: 10px; min-width: 350px; position: relative;">
                    <button style="position: absolute; right: 15px; top: 10px; background: none; border: none; font-size: 22px; cursor: pointer; color: #888;" onclick="this.closest('.edit-user-modal').remove()">&times;</button>
                    <h3 style="margin-bottom: 20px;">编辑用户</h3>
                    <form id="editUserForm">
                        <input type="hidden" name="id" value="${user.id}">
                        <div style="margin-bottom: 15px;">
                            <label>用户名：</label><br>
                            <input type="text" name="username" value="${user.username}" required style="width: 100%; padding: 6px 10px;">
                        </div>
                        <div style="margin-bottom: 15px;">
                            <label>邮箱：</label><br>
                            <input type="email" name="email" value="${user.email || ''}" style="width: 100%; padding: 6px 10px;">
                        </div>
                        <div style="margin-bottom: 15px;">
                            <label>电话：</label><br>
                            <input type="text" name="phone" value="${user.phone || ''}" style="width: 100%; padding: 6px 10px;">
                        </div>
                        <div style="margin-bottom: 15px;">
                            <label>密码：</label><br>
                            <input type="password" name="password" value="" placeholder="如需修改请输入新密码" style="width: 100%; padding: 6px 10px;">
                        </div>
                        <div style="text-align: right;">
                            <button type="button" onclick="this.closest('.edit-user-modal').remove()" style="margin-right: 10px;">取消</button>
                            <button type="submit">保存</button>
                        </div>
                    </form>
                </div>
            `;
            modal.className = 'edit-user-modal';
            document.body.appendChild(modal);
            // 表单提交
            modal.querySelector('#editUserForm').onsubmit = async function (e) {
                e.preventDefault();
                const form = e.target;
                const updatedUser = {
                    id: user.id,
                    username: form.username.value,
                    email: form.email.value,
                    phone: form.phone.value
                };
                if (form.password.value) {
                    updatedUser.password = form.password.value;
                }
                console.log('提交用户信息:', updatedUser);
                // 修改用户信息
                try {
                    const resp = await fetch('/updateUser', {
                        method: 'PUT',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(updatedUser)
                    });
                    let result;
                    try {
                        result = await resp.json();
                    } catch {
                        result = await resp.text();
                    }
                    console.log('后端返回:', result);
                    if (result === 1 || result.success === true) {
                        alert('用户信息更新成功！');
                        modal.remove();
                        loadUsers();
                    } else {
                        alert('更新失败：' + (result.message || result));
                    }
                } catch (error) {
                    alert('更新失败，请重试');
                    console.error('更新用户异常:', error);
                }
            };
        }
        //删除用户
        async function deleteUser(id) {
            if (!confirm('确定要删除这个用户吗？')) return;
            try {
                const resp = await fetch(`/deleteUser?id=${id}`, { method: 'DELETE' });
                const result = await resp.text();
                if (result.includes('成功')) {
                    alert('用户删除成功！');
                    loadUsers();
                } else {
                    alert('删除失败：' + result);
                }
            } catch (error) {
                alert('删除失败，请重试');
            }
        }

        // 图片上传逻辑 - 使用事件委托监听所有图片上传input
        document.addEventListener('change', async function (e) {
            if (e.target.name === 'image' && e.target.type === 'file') {
                const file = e.target.files[0];
                if (!file) return;

                const formData = new FormData();
                formData.append('image', file);

                try {
                    const resp = await fetch('/api/upload', {
                        method: 'POST',
                        body: formData
                    });
                    const data = await resp.json();
                    if (data.success) {
                        // 找到对应的隐藏域并设置值
                        const modal = e.target.closest('.modal');
                        const imageUrlInput = modal.querySelector('input[name="imageUrl"]');
                        if (imageUrlInput) {
                            imageUrlInput.value = data.url;
                        }

                        // 显示图片预览
                        showImagePreview(e.target, data.url);
                    } else {
                        alert('图片上传失败：' + data.message);
                    }
                } catch (error) {
                    console.error('上传错误:', error);
                    alert('图片上传失败，请重试');
                }
            }
        });

        // 显示图片预览
        function showImagePreview(input, imageUrl) {
            // 移除之前的预览
            const existingPreview = input.parentNode.querySelector('.image-preview');
            if (existingPreview) {
                existingPreview.remove();
            }

            // 创建预览元素
            const preview = document.createElement('div');
            preview.className = 'image-preview';
            preview.style.cssText = `
                margin-top: 10px;
                text-align: center;
            `;

            const img = document.createElement('img');
            img.src = imageUrl;
            img.style.cssText = `
                max-width: 150px;
                max-height: 150px;
                border-radius: 4px;
                border: 1px solid #ddd;
            `;
            img.onerror = function () {
                this.style.display = 'none';
                preview.innerHTML = '<p style="color: #999; font-size: 12px;">图片加载失败</p>';
            };

            preview.appendChild(img);
            input.parentNode.appendChild(preview);
        }

        // 新增商品提交
        const addProductForm = document.getElementById('addProductForm');
        addProductForm.addEventListener('submit', async function (e) {
            e.preventDefault();
            const product = {
                name: this.name.value,
                price: parseFloat(this.price.value),
                stock: parseInt(this.stock.value),
                categoryId: parseInt(this.categoryId.value),
                description: this.description.value,
                imageUrl: this.imageUrl.value
            };
            const response = await fetch('/api/products', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(product)
            });
            const data = await response.json();
            if (data.success) {
                alert('商品添加成功！');
                closeModal('addProductModal');
                loadProducts(); // 添加成功后自动刷新
            } else {
                alert('添加失败：' + data.message);
            }
        });

        // 渲染订单表格
        function renderOrdersTable(data) {
            const container = document.getElementById('orders-table-container');
            if (!data || data.length === 0) {
                container.innerHTML = '<div class="empty-state"><div>🛒</div><p>没有找到任何订单。</p></div>';
                return;
            }

            // 显示订单
            const orders = data.reduce((acc, item) => {
                if (!acc[item.orderId]) {
                    acc[item.orderId] = {
                        id: item.orderId,
                        user: item.username,
                        total: item.totalAmount,
                        status: item.status,
                        date: new Date(item.createdAt).toLocaleString(),
                        items: []
                    };
                }
                acc[item.orderId].items.push(item);
                return acc;
            }, {});

            let tableHTML = `
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>订单ID</th>
                            <th>用户名</th>
                            <th>商品详情</th>
                            <th>总金额</th>
                            <th>状态</th>
                            <th>下单时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
            `;

            for (const orderId in orders) {
                const order = orders[orderId];
                const statusText = order.status === 0 ? '未配送' : '已配送';
                const statusClass = order.status === 0 ? 'status-pending' : 'status-shipped';

                let itemsHTML = order.items.map(p =>
                    `<div style="white-space: nowrap;">- ${p.productName} (x${p.quantity})</div>`
                ).join('');

                tableHTML += `
                    <tr id="order-row-${order.id}">
                        <td>${order.id}</td>
                        <td>${order.user}</td>
                        <td>${itemsHTML}</td>
                        <td>¥${order.total.toFixed(2)}</td>
                        <td><span class="status-badge ${statusClass}">${statusText}</span></td>
                        <td>${order.date}</td>
                        <td>
                            ${order.status === 0 ? `<button class="action-btn ship-btn" onclick="shipOrder(${order.id})">标记为发货</button>` : '无需操作'}
                        </td>
                    </tr>
                `;
            }

            tableHTML += `</tbody></table>`;
            container.innerHTML = tableHTML;
        }

        // 发货操作
        async function shipOrder(orderId) {
            if (!confirm(`确定要将订单 #${orderId} 标记为已发货吗？`)) return;

            const shipButton = event.target;
            shipButton.disabled = true;
            shipButton.innerHTML = '<span class="spinner"></span>';

            try {
                const response = await fetch('/orders/' + orderId + '/ship', {
                    method: 'PUT',
                });
                const resultText = await response.text();

                if (response.ok && resultText.includes('成功')) {
                    // 更新UI
                    const row = document.getElementById('order-row-' + orderId);
                    const statusCell = row.querySelector('.status-badge');
                    statusCell.textContent = '已配送';
                    statusCell.className = 'status-badge status-shipped';
                    shipButton.replaceWith('无需操作');
                } else {
                    throw new Error(resultText || '操作失败');
                }
            } catch (error) {
                console.error('Ship order error:', error);
                alert('操作失败: ' + error.message);
                shipButton.disabled = false;
                shipButton.innerHTML = '标记为发货';
            }
        }
    </script>
</body>

</html>